package whisper.service.repository.impl;

import com.google.common.base.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import whisper.service.domain.db.TargetMedia;
import whisper.service.repository.TargetMediaRepository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by JT on 2017/11/18.
 */
@Repository
public class TargetMediaRepositoryImpl implements TargetMediaRepository {

    private static final String TABLE_NAME_WM_TARGET = "WM_TARGET";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public long saveTargetMedia(TargetMedia targetMedia) {
        String sql = String.format("INSERT INTO %s(TARGETNAME, TARGETPATH, TARGETSIZE, WIDTH, HEIGHT) VALUES(?, ?, ?, ?, ?)",
                TABLE_NAME_WM_TARGET);
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            PreparedStatement ps = null;
            @Override
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, Optional.fromNullable(targetMedia.getTargetName()).or(""));
                ps.setString(2, Optional.fromNullable(targetMedia.getTargetPath()).or(""));
                ps.setString(3, Optional.fromNullable(targetMedia.getTargetSize()).or(""));
                ps.setString(4, Optional.fromNullable(targetMedia.getWidth()).or(""));
                ps.setString(5, Optional.fromNullable(targetMedia.getHeight()).or(""));
                return ps;
            }
        }, keyHolder);
        return keyHolder.getKey().longValue();
    }
}
